package cn.sdormitory.common.utils;

import com.alibaba.fastjson.JSON;
import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.AppSigner;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 使用AI技术 识别图片中的文字，并提取所需要的信息
 */
@Slf4j
public class ImageToTextAIUtils {

    private static String appID = "DoIzHtocHeBR88rLlgETvYVC";
    private static String appKey="GZhHU9PcjphnwKav7fIionIwokueumyL";

    public static String getImageDoc(String token,String imgPath){
        String path = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token="+token;
        Map<String,String> headerMap = new HashMap<String, String>();
        headerMap.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

        try {
            byte[] imageByteArray = FileUtil.read(imgPath);
            String imageBase64 = new String(Base64.encodeBase64(imageByteArray), "UTF-8");
            String result = OkHttpUtil.doPost1(path, headerMap, "image="+URLEncoder.encode(imageBase64,"UTF-8"));

            // 返回结果格式为Json字符串
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getAuth() {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + appID
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + appKey;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            Map<String,Object> resultMap = JSON.parseObject(result,Map.class);

            return String.valueOf(resultMap.get("access_token"));
        } catch (Exception e) {
            System.err.printf("获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }

    /**
     * 从解析的结果中，识别出指定内容
     * @param words
     * @param type
     * @return
     */
    public static List<String> getRecognitionWordsList(List<Map<String,String>> words, String type){
        if(words==null || words.size()==0){
            return null;
        }
        List<String> resultList = new ArrayList<>();
        log.info("words: {}",words);
        for(Map<String,String> map : words){
            String word = map.get("words");
            String str = null;
            if("1".equals(type)){
                //生产日期
                str = getDateOfManufacture(word);
            }
            if("2".equals(type)){
                //保质期
                str = validityDay(word);
            }
            if("3".equals(type)){
                //生产商
                str = goodsManufacturer(word);
            }

            if(!org.springframework.util.StringUtils.isEmpty(str)){
                resultList.add(str);
            }

        }
        return resultList;
    }

    /**
     * 获取到生产日期
     * @param word
     * @return
     */
    private static String getDateOfManufacture(String word){
        //去掉汉字
        String removeChinese = removeChineseCharacters(word);
        //去掉字母
        String removeLetter = removeLetter(removeChinese);
        //去掉特殊符号
        String removeSymbol = getIdByString(removeLetter);
        try{
            if(removeSymbol.length()<8){
                return null;
            }
            if(removeSymbol.startsWith("202")){
                //只去8个数yyyyMMdd
                String newStr = removeSymbol.substring(0,8);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                //严格验证日期格式
                sdf.setLenient(false);
                sdf.parse(newStr);
                return newStr;
            }

        }catch(Exception e){
            log.error("时间格式错误:{}",word);
        }
        return null;
    }

    private static String goodsManufacturer(String word){
        String keyWord[]={"委托方：","生产企业：","生产商："};
        for (String key:keyWord){
            if(word.startsWith(key)){
                return word.substring(key.length());
            }
        }
        return null;
    }

    /**
     * 获取到保质期
     * @param word
     * @return
     */
    private static String validityDay(String word){
        String keyWord[]={"保质期："};
        for (String key:keyWord){
            if(word.indexOf(key)>=0){
                return splitWord(word,key);
            }
        }
        return null;
    }

    private static String splitWord(String word,String keyWord){
        String dateFlags[]={"年","个月","月","日","天"};
        int dateDays[]={365,30,30,1,1};
        int day = 0;
        int keyIndex = word.indexOf(keyWord);
        //word = word.replaceAll(keyWord,"");
        for(int i=0;i<dateFlags.length;i++){
            int index = word.indexOf(dateFlags[i]);
            if(word.indexOf(dateFlags[i])>0){
                String charWord = word.substring(keyIndex+keyWord.length(),index).trim();
                if(!org.apache.commons.lang3.StringUtils.isNumeric(charWord)){
                    day = ChineseToNumberUtil.toNumber(charWord) * dateDays[i];
                }else{
                    return String.valueOf(Integer.valueOf(charWord)* dateDays[i]);
                }

                return String.valueOf(day);
            }
        }
        return String.valueOf(day);
    }


    public static String getIdByString(String nameAndId) {
        String id = removeChineseCharacters(nameAndId);
        id = StringUtils.replace(id,"(","");
        id = StringUtils.replace(id,")","");
        id = StringUtils.replace(id,"-","");
        id = StringUtils.replace(id,"[","");
        id = StringUtils.replace(id,"]","");
        id = StringUtils.replace(id,"：","");
        id = StringUtils.replace(id,"%","");
        return id;
    }

    /**
     * 去掉汉字
     * @param nameAndId
     * @return
     */
    public static  String removeChineseCharacters (String nameAndId) {
        String chinese = "[\u4e00-\u9fa5]";
        //汉字字符集
        Pattern p = Pattern.compile(chinese);
        Matcher m = p.matcher(nameAndId);
        String id = m.replaceAll("");
        return id;
    }

    /**
     * 去掉字母
     * @param nameAndId
     * @return
     */
    public  static String removeLetter (String nameAndId) {
        String chinese = "[a-zA-Z]";
        //字母
        Pattern p = Pattern.compile(chinese);
        Matcher m = p.matcher(nameAndId);
        String id = m.replaceAll("");
        return id;
    }

    /**
     * 当前城市的天气
     * @return
     */
    public static String currentCityWeather(){
        // 获取token地址
        String dayUrl = "https://weather.api.bdymkt.com/day";
        ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.GET, dayUrl);
        request.setCredentials("cc3fa02e46cc41b9b90dac8165839572", "e212e7ec11b14369a8cf9eeee48afa4a");

        request.addHeaderParameter("Content-Type", "application/json;charset=UTF-8");
        request.addQueryParameter("city", "岳阳");
        request.addQueryParameter("province", "湖南");

        ApiExplorerClient client = new ApiExplorerClient(new AppSigner());

        try {
            ApiExplorerResponse response = client.sendRequest(request);
            // 返回结果格式为Json字符串
            System.out.println(response.getResult());
            return response.getResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
       String result = ImageToTextAIUtils.currentCityWeather();
        System.out.println(result);
    }

}
